package services

import (
	"demo/models"
	"demo/pkg/database"
	"demo/pkg/notice"
	"demo/utils"
	"fmt"
	"math"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

/*
阶梯电价按年用电量分为三档阶梯式累进加价。 其中第一档电量为年用电量2760度 (月均用电量为230度)及以下的，电价不调整，
仍为每度0.538元;第二档电量为年用电量2761-4800度的，电价在第一档的基础上加0.05元，
为每度0.588元;第三档电量为年用电量4800度 (月均用电量为400度)以上的，电价在第一档的基础上加0.3元，为每度0.838元。
*/
// 定义电价阶梯
const (
	firstTierUsage   = 230.0 // 第一档月均用电量下限，单位：度
	secondTierUsage  = 400.0 // 第二档月均用电量下限，单位：度
	electricityRate1 = 0.538 // 第一档电价，每度电费率，单位：元
	electricityRate2 = 0.588 // 第二档电价，每度电费率，单位：元
	electricityRate3 = 0.838 // 第三档电价，每度电费率，单位：元
)

// 计算电费（由管理员调用）
func CalculateElectricityBillService(c *gin.Context) {
	var req struct {
		UserId int     `json:"user_id" binding:"required"`
		Usage  float32 `json:"usage" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	resp := models.GetDefaultResp()

	// 调用服务层逻辑计算电费
	bill, err := calculateElectricityBill(req.UserId, req.Usage)
	if err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}

	// 将计算后的账单保存到数据库
	err = database.InsertElectricityBill(&bill)
	if err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}

	resp.Data = bill
	sendBillToUser(c, &bill)
	c.JSON(http.StatusOK, resp)
}

func calculateElectricityBill(userId int, monthlyUsage float32) (models.ElectricityBills, error) {
	var rate float64

	// 根据月均用电量判断所处的电价档次
	if monthlyUsage <= firstTierUsage {
		rate = electricityRate1
	} else if monthlyUsage > firstTierUsage && monthlyUsage <= secondTierUsage {
		rate = electricityRate2
	} else {
		rate = electricityRate3
	}

	amount := float32(math.Round(float64(monthlyUsage)*rate*100)) / 100

	// 创建电费账单对象
	bill := models.ElectricityBills{
		UserId:           userId,
		EleId:            generateEleId(),
		BillDate:         time.Now(),
		ElectricityUsage: monthlyUsage,
		Amount:           amount,
		ElePayment:       0,
		EleBalanceBefore: 0,
		EleBalanceNow:    0,
		PayTime:          time.Time{},
		Status:           "unpaid",
		DueDate:          time.Now().AddDate(0, 0, 30),
	}

	return bill, nil
}

// 查询电费账单
func GetElectricityBillsService(c *gin.Context) {
	user := getUserInfo(c)
	resp := models.GetDefaultResp()

	// 调用数据库层查询电费账单
	bills, err := database.GetElectricityBillsByUserId(user.Id)
	if err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}

	resp.Data = bills
	c.JSON(http.StatusOK, resp)
}

// 支付电费
func PayElectricityBillService(c *gin.Context) {
	var req struct {
		BillId        int     `json:"bill_id" binding:"required"`
		Amount        float32 `json:"amount" binding:"required"`
		PaymentMethod string  `json:"payment_method" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	user := getUserInfo(c)
	resp := models.GetDefaultResp()

	// 调用服务层逻辑缴纳电费
	payment, err := database.PayElectricityBill(user.Id, req.BillId, req.Amount, req.PaymentMethod)
	if err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}

	formattedAmount := fmt.Sprintf("%.2f", payment.Amount)
	url := utils.AliPay(&payment,formattedAmount, c)
	resp.Data = url
	c.JSON(http.StatusOK, resp)
}

// 生成唯一的电费账单ID
func generateEleId() string {
	return "ELE-" + strconv.FormatInt(time.Now().UnixNano(), 10)
}

// 发送账单给用户
func sendBillToUser(c *gin.Context, bill *models.ElectricityBills) {
	user, _ := database.GetUserinfoByUserId(bill.UserId)
	if user == nil {
		logrus.Errorln("failed to get user info")
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get user info"})
		return
	}

	// 生成账单通知的标题和内容
	title := "【原始人电力公司】您的电费账单"
	content := fmt.Sprintf(
		"尊敬的用户，\n\n"+
			"您好！感谢您使用原始人电力公司的服务。以下是您本期的电费账单详情：\n\n"+
			"账单编号: %s\n"+
			"账单日期: %s\n"+
			"用电量: %.2f 度\n"+
			"应缴金额: %.2f 元\n"+
			"已缴金额: %.2f 元\n"+
			"账单状态: %s\n"+
			"到期日期: %s\n\n"+
			"请及时缴纳您的电费。如有任何疑问，请联系原始人电力公司客服。\n\n"+
			"谢谢！\n原始人电力公司",
		bill.EleId,
		bill.BillDate.Format("2006-01-02 15:04:05"),
		bill.ElectricityUsage,
		bill.Amount,
		bill.ElePayment,
		bill.Status,
		bill.DueDate.Format("2006-01-02 15:04:05"),
	)

	noticeMsg := &models.NoticeMsg{
		Title:    title,
		Content:  content,
		UserNums: []string{user.Email},
		Type:     "email",
	}

	err := notice.SendNoticeToUser(noticeMsg)
	if err != nil {
		return
	}
	//插入notice表中的结构体
	notice := models.Notifications{
		UserId:    user.Id,
		Message:   content,
		IsRead:    0,
		Timestamp: time.Now(),
	}
	err = database.InsertOneNotice(&notice)
	if err != nil {
		return
	}
}

func GetAllBills(c *gin.Context) {
	resp := models.GetDefaultResp()
	// 调用数据库层查询电费账单
	bills, err := database.GetAllBills()
	if err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}
	resp.Data = bills
	c.JSON(http.StatusOK, resp)
}


//获取所有支付信息
func GetAllPayments(c *gin.Context) {
	resp := models.GetDefaultResp()
	// 调用数据库层查询电费支付账单
	payments, err := database.GetAllPayments()
	if err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}
	resp.Data = payments
	c.JSON(http.StatusOK, resp)
}